package com.zhangxiaofanfan.hotcode.first;

/**
 * <a href="https://leetcode.cn/problems/number-of-islands/description/?envType=study-plan-v2&envId=top-100-liked">200. 岛屿数量</a>
 *
 * @author zhangxiaofanfan
 * @date 2024-06-26 20:33:33
 */
public class HotCode051 {
    public static void main(String[] args) {

    }

    public int numIslands(char[][] grid) {
        int row = grid.length;
        int col = grid[0].length;
        boolean[][] map = new boolean[row][col];
        int rowIndex, colIndex, areaCount = 0;
        for (rowIndex = 0; rowIndex < row; rowIndex++) {
            for (colIndex = 0; colIndex < col; colIndex++) {
                if (grid[rowIndex][colIndex] == '1' && !map[rowIndex][colIndex]) {
                    bfs(grid, rowIndex, colIndex, map);
                    areaCount++;
                }
                map[rowIndex][colIndex] = true;
            }
        }

        return areaCount;
    }

    public void bfs(char[][] grid, int rowIndex, int colIndex, boolean[][] map) {
        if (rowIndex < 0 || rowIndex >= grid.length || colIndex < 0 || colIndex >= grid[0].length || grid[rowIndex][colIndex] == '0' || map[rowIndex][colIndex]) {
            return;
        }
        map[rowIndex][colIndex] = true;
        bfs(grid, rowIndex + 1, colIndex, map);
        bfs(grid, rowIndex - 1, colIndex, map);
        bfs(grid, rowIndex, colIndex + 1, map);
        bfs(grid, rowIndex, colIndex - 1, map);
    }
}
